package com.ruoyi.project.modules.page.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.project.modules.category.domain.Category;
import com.ruoyi.project.modules.category.service.ICategoryService;
import com.ruoyi.project.modules.fileInfo.domain.FileInf;
import com.ruoyi.project.modules.fileInfo.service.IFileInfoService;
import com.ruoyi.project.modules.interfaceObject.domain.InterfaceObject;
import com.ruoyi.project.modules.interfaceObject.service.IInterfaceObjectService;
import com.ruoyi.project.modules.interfaceinfo.domain.InterfaceInfo;
import com.ruoyi.project.modules.interfaceinfo.domain.VirtualUsage;
import com.ruoyi.project.modules.interfaceinfo.request.BffImgReq;
import com.ruoyi.project.modules.interfaceinfo.service.IInterfaceInfoService;
import com.ruoyi.project.modules.interfaceinfo.service.IVirtualUsageService;
import com.ruoyi.project.modules.interfaceinfo.vo.InterfaceUser;
import com.ruoyi.project.modules.product.domain.ProductInfo;
import com.ruoyi.project.modules.product.service.IProductInfoService;
import com.ruoyi.project.modules.productVersionObejct.domain.ProductVersionObejct;
import com.ruoyi.project.modules.productVersionObejct.service.IProductVersionObejctService;
import com.ruoyi.project.modules.table.domain.TableInfo;
import com.ruoyi.project.modules.table.service.ITableInfoService;
import com.ruoyi.project.modules.usage.domain.Usage;
import com.ruoyi.project.modules.usage.service.IUsageService;
import com.ruoyi.project.modules.userDataAuth.service.IUserDataAuthService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.project.modules.page.domain.Page;
import com.ruoyi.project.modules.page.service.IPageService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.Ztree;

import javax.annotation.Resource;

/**
 * 页面Controller
 *
 * @author smallrain
 * @date 2021-11-06
 */
@Controller
@RequestMapping("/page/page")
public class PageController extends BaseController {
    private String prefix = "page/page";

    @Autowired
    private IPageService pageService;

    @Autowired
    private IProductVersionObejctService productVersionObejctService;
    @Autowired
    private IProductInfoService productInfoService;

    @RequiresPermissions("page:page:view")
    @GetMapping()
    public String page(ModelMap mmap) {
//        Category category = new Category();
//        category.setParentId(0L);
//        category.setSystemType("2");
//        List<Category> categories = categoryService.selectCategoryList(category);
//        if (CollectionUtil.isNotEmpty(categories)) {
//            mmap.put("category", categories.get(0));
//        } else {
//            mmap.put("category", new Category());
//        }

        return prefix + "/page";
    }

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IFileInfoService fileInfoService;

    /**
     * 查询页面树列表
     */
    @RequiresPermissions("page:page:list")
    @PostMapping("/list")
    @ResponseBody
    public List<Page> list(Page page) {
        page.setUserId(ShiroUtils.getSysUser().getUserId());
        page.setFlag(this.getFlag());
        List<Page> list = pageService.selectPageList(page);
        if (CollectionUtil.isNotEmpty(list)) {
            List<Long> objectIds = list.stream().map(Page::getId).collect(Collectors.toList());
            FileInf fileInf = new FileInf();
            fileInf.setObjectType("2");
            fileInf.setImgType(null);
            fileInf.setObjectIds(objectIds);
            List<FileInf> fileInfs = this.fileInfoService.selectFileInfoList(fileInf);
            if (CollectionUtil.isNotEmpty(fileInfs)) {
                Map<Long, List<FileInf>> collect = fileInfs.stream().collect(Collectors.groupingBy(FileInf::getObjectId));
                for (Page page1 : list) {
                    List<FileInf> fileInfList = collect.get(page1.getId());
                    if (CollectionUtil.isNotEmpty(fileInfList)) {
                        List<FileInf> componentFileInfList = new ArrayList<>();
                        Iterator<FileInf> iterator = fileInfList.iterator();
                        while (iterator.hasNext()) {
                            FileInf next = iterator.next();
                            if ("2".equals(next.getImgType())) {
                                componentFileInfList.add(next);
                                iterator.remove();
                            }
                        }
                        page1.setComponentFileInfList(componentFileInfList);
                    }
                    page1.setFileInfList(fileInfList);
                }
            }
        }
        return list;
    }

    /**
     * 导出页面列表
     */
    @RequiresPermissions("page:page:export")
    @Log(title = "页面", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Page page) {
        List<Page> list = pageService.selectPageList(page);
        ExcelUtil<Page> util = new ExcelUtil<Page>(Page.class);
        return util.exportExcel(list, "页面数据");
    }

    @Autowired
    private IInterfaceInfoService interfaceInfoService;

    @Autowired
    private IInterfaceObjectService interfaceObjectService;

    /**
     * 新增页面
     */
    @GetMapping(value = {"/add/{id}", "/add/"})
    public String add(@PathVariable(value = "id", required = false) Long id, ModelMap mmap) {
        if (StringUtils.isNotNull(id)) {
            mmap.put("page", pageService.selectPageById(id));
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setFbType("2");
        List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        mmap.put("interfaceInfoList", interfaceInfoList);
        return prefix + "/add";
    }

    /**
     * 新增保存页面
     */
    @RequiresPermissions("page:page:add")
    @Log(title = "页面", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Page page) {
        return toAjax(pageService.insertPage(page));
    }

    /**
     * 修改页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        Page page = pageService.selectPageById(id);
        mmap.put("page", page);
        if (page != null) {
            Category category = this.categoryService.selectCategoryById(page.getCategoryId());
            mmap.put("category", category == null ? new Category() : category);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setFbType("2");
        List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        mmap.put("interfaceInfoList", interfaceInfoList);

        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectId(id);
        interfaceObject.setObjectType("2");
        List<InterfaceObject> interfaceObjects = interfaceObjectService.selectInterfaceObjectList(interfaceObject);
        if (CollectionUtil.isNotEmpty(interfaceObjects)) {
            List<Long> interfaceIds = new ArrayList<>();
            interfaceObjects.forEach(ib -> interfaceIds.add(ib.getInterfaceId()));
            mmap.put("interfaceIds", interfaceIds);
        }


        ProductVersionObejct productVersionObejct = new ProductVersionObejct();
        productVersionObejct.setObjectType("2");
        productVersionObejct.setObjectId(id);
        List<Long> productIds = new ArrayList<>();
        List<ProductVersionObejct> productVersionObejcts = this.productVersionObejctService.selectProductVersionObejctList(productVersionObejct);
        if(CollectionUtil.isNotEmpty(productVersionObejcts)) {
            productIds = productVersionObejcts.stream().map(ProductVersionObejct::getTableProductVersionId).collect(Collectors.toList());
        }
        mmap.put("productIds", productIds);
        ProductInfo productInfo = new ProductInfo();
        productInfo.setVersionType("2");
        List<ProductInfo> productList = this.productInfoService.selectProductInfoList(productInfo);
        mmap.put("productList", productList);

        return prefix + "/edit";
    }

    /**
     * 修改保存页面
     */
    @RequiresPermissions("page:page:edit")
    @Log(title = "页面", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Page page) {
        return toAjax(pageService.updatePage(page));
    }

    /**
     * 删除
     */
    @RequiresPermissions("page:page:remove")
    @Log(title = "页面", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{id}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("id") Long id) {
        return toAjax(pageService.deletePageById(id));
    }

    /**
     * 选择页面树
     */
    @GetMapping(value = {"/selectPageTree/{id}", "/selectPageTree/"})
    public String selectPageTree(@PathVariable(value = "id", required = false) Long id, ModelMap mmap) {
        if (StringUtils.isNotNull(id)) {
            mmap.put("page", pageService.selectPageById(id));
        }
        return prefix + "/tree";
    }

    /**
     * 加载页面树列表
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        List<Ztree> ztrees = pageService.selectPageTree();
        return ztrees;
    }

    @Resource
    private IVirtualUsageService virtualUsageService;

    @Resource
    private ITableInfoService tableInfoService;

    @GetMapping("/tableList")
    public String tableList(@RequestParam Long id, ModelMap mmap) {
        Page page = this.pageService.selectPageById(id);
        mmap.put("page", page);
        if (page != null) {
            Category category = this.categoryService.selectCategoryById(page.getCategoryId());
            mmap.put("category", category == null ? new Category() : category);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setFbType("2");
        List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        mmap.put("interfaceInfoList", interfaceInfoList);
        // 查询接口
        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectId(id);
        interfaceObject.setObjectType("2");
        List<InterfaceObject> interfaceObjects = interfaceObjectService.selectInterfaceObjectList(interfaceObject);
        if (CollectionUtil.isNotEmpty(interfaceObjects)) {
            Set<Long> interfaceIds = new HashSet<>();
            interfaceObjects.forEach(ib -> interfaceIds.add(ib.getInterfaceId()));
            mmap.put("interfaceIds", interfaceIds);

            // 查询dubbo
            VirtualUsage virtualUsage = new VirtualUsage();
            virtualUsage.setRelationInterfaceIds(interfaceIds);
            List<VirtualUsage> virtualUsages = this.virtualUsageService.selectVirtualUsageList(virtualUsage);
            if (CollectionUtil.isNotEmpty(virtualUsages)) {
                Set<Long> dubboIds = virtualUsages.stream().map(a -> a.getInterfaceId()).collect(Collectors.toSet());
                // 查询表id
                InterfaceObject interfaceObject2 = new InterfaceObject();
                interfaceObject2.setDubboIds(dubboIds);
                interfaceObject2.setObjectType("1");
                List<InterfaceObject> interfaceObjectList = this.interfaceObjectService.selectInterfaceObjectList(interfaceObject2);
                if (CollectionUtil.isNotEmpty(interfaceObjectList)) {
                    Set<Long> tableIds = interfaceObjectList.stream().map(a -> a.getObjectId()).collect(Collectors.toSet());
                    TableInfo tableInfo = new TableInfo();
                    tableInfo.setTableIds(tableIds);
                    List<TableInfo> tableList = this.tableInfoService.selectTableInfoList(tableInfo);
                    mmap.put("tableList", tableList);
                }
            }
        }
        return prefix + "/tableList";
    }

    @Autowired
    private IUsageService usageService;

    @GetMapping("/usageList")
    public String usageList(@RequestParam Long id, ModelMap mmap) {
        Page page = this.pageService.selectPageById(id);
        mmap.put("page", page);
        if (page != null) {
            Category category = this.categoryService.selectCategoryById(page.getCategoryId());
            mmap.put("category", category == null ? new Category() : category);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setFbType("2");
        List<InterfaceInfo> interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        mmap.put("interfaceInfoList", interfaceInfoList);
        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectId(id);
        interfaceObject.setObjectType("2");
        // 查询接口
        List<InterfaceObject> interfaceObjects = interfaceObjectService.selectInterfaceObjectList(interfaceObject);
        if (CollectionUtil.isNotEmpty(interfaceObjects)) {
            Set<Long> interfaceIds = new HashSet<>();
            interfaceObjects.forEach(ib -> interfaceIds.add(ib.getInterfaceId()));
            mmap.put("interfaceIds", interfaceIds);

            // 通过接口，查询用况
            InterfaceObject interfaceObject2 = new InterfaceObject();
            interfaceObject2.setBffIds(interfaceIds);
            interfaceObject2.setObjectType("3");
            List<InterfaceObject> interfaceObjectList = interfaceObjectService.selectInterfaceObjectList(interfaceObject2);
            if (CollectionUtil.isNotEmpty(interfaceObjectList)) {
                Set<Long> usageIds = new HashSet<>();
                interfaceObjectList.forEach(ib -> usageIds.add(ib.getObjectId()));

                Usage usage = new Usage();
                usage.setUsageIds(usageIds);
                List<Usage> usageList = usageService.selectUsageList(usage);
                mmap.put("usageList", usageList);
            }
        }
        return prefix + "/usageList";
    }

    @GetMapping("add_img/{pageId}/{imgType}")
    public String add_bff_img(@PathVariable("pageId") Long pageId,
                              @PathVariable("imgType") String imgType,
                              @RequestParam(value = "imageId",required = false,defaultValue = "0") Long imageId,
                              ModelMap mmap) {
        mmap.put("pageId", pageId);
        mmap.put("imgType", imgType);
        mmap.put("imageId", imageId);
        return prefix + "/add_img";
    }

    /**
     * 添加 图片
     * @param page
     * @return
     */
    @PostMapping("/addImg")
    @ResponseBody
    public AjaxResult addImg(@RequestBody Page page) {
        this.pageService.addImg(page);
        return success();
    }

    @Autowired
    private IUserDataAuthService userDataAuthService;

    @GetMapping("/detail/{id}")
    public String details(@PathVariable("id") Long id, ModelMap mmap) {
        Page page = this.pageService.selectPageById(id);
        mmap.put("page", page);
        List<InterfaceUser> interfaceUsers = this.userDataAuthService.selectInterfaceUser(id, "3");
        if (CollectionUtil.isNotEmpty(interfaceUsers)) {
            for (InterfaceUser interfaceUser : interfaceUsers) {
                if (ShiroUtils.getLoginName().equals(interfaceUser.getLoginName())) {
                    mmap.put("owner", true);
                    mmap.put("interfaceUser", interfaceUser);

                    if (interfaceUser.getObjectStatus() == 0) {
                        mmap.put("statusName", "未开始");
                    } else if (interfaceUser.getObjectStatus() == 1) {
                        mmap.put("statusName", "进行中");
                    } else if (interfaceUser.getObjectStatus() == 2) {
                        mmap.put("statusName", "已完成");
                    }
                    break;
                }
            }
        }
        return prefix + "/details";
    }

    @PostMapping("/bffList")
    @ResponseBody
    public AjaxResult bffList(@RequestParam Long pageId) {
        List<InterfaceInfo> interfaceInfoList = new ArrayList<>();
        List<Long> interfaceIds = getInterfaceIds(pageId);
        if (CollectionUtil.isNotEmpty(interfaceIds)) {
            InterfaceInfo interfaceInfo = new InterfaceInfo();
            interfaceInfo.setIds(interfaceIds);
            interfaceInfoList = this.interfaceInfoService.selectInterfaceInfoList(interfaceInfo);
        }
        return AjaxResult.success(interfaceInfoList);
    }

    private List<Long> getInterfaceIds(Long pageId) {
        InterfaceObject interfaceObject = new InterfaceObject();
        interfaceObject.setObjectType("2");
        interfaceObject.setObjectId(pageId);
        List<InterfaceObject> interfaceObjectList = this.interfaceObjectService.selectInterfaceObjectList(interfaceObject);
        if (CollectionUtil.isNotEmpty(interfaceObjectList)) {
            return interfaceObjectList.stream().map(InterfaceObject::getInterfaceId).collect(Collectors.toList());
        }
        return null;
    }

    @PostMapping("/usageList")
    @ResponseBody
    public AjaxResult usageList(@RequestParam Long pageId) {
        List<Usage> usageList = new ArrayList<>();
        List<Long> interfaceIds = getInterfaceIds(pageId);
        if (CollectionUtil.isNotEmpty(interfaceIds)) {
            InterfaceObject interfaceObject = new InterfaceObject();
            interfaceObject.setObjectType("3");
            interfaceObject.setBffIds(new HashSet<>(interfaceIds));
            List<InterfaceObject> interfaceObjectList = this.interfaceObjectService.selectInterfaceObjectList(interfaceObject);
            if (CollectionUtil.isNotEmpty(interfaceObjectList)) {
                Set<Long> usageIds = interfaceObjectList.stream().map(InterfaceObject::getObjectId).collect(Collectors.toSet());

                Usage usage = new Usage();
                usage.setUsageIds(usageIds);
                usageList = this.usageService.selectUsageList(usage);
            }
        }
        return AjaxResult.success(usageList);
    }

    @PostMapping("/tableList")
    @ResponseBody
    public AjaxResult tableList(@RequestParam Long pageId) {
        List<Long> interfaceIds = getInterfaceIds(pageId);
        List<TableInfo> tableInfos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(interfaceIds)) {
            List<Long> tableIds = this.pageService.tableList(interfaceIds);
            if (CollectionUtil.isNotEmpty(tableIds)) {
                tableInfos = this.tableInfoService.selectTableInfoByTableIds(tableIds);
            }
        }
        return AjaxResult.success(tableInfos);
    }

    @PostMapping("/imgList")
    @ResponseBody
    public AjaxResult imgList(@RequestParam Long pageId) {
        FileInf fileInf = new FileInf();
        fileInf.setObjectId(pageId);
        fileInf.setObjectType("2");
        fileInf.setImgType(null);
        List<FileInf> fileInfs = this.fileInfoService.selectFileInfoList(fileInf);
        List<FileInf> commonImgList = new ArrayList<>();
        List<FileInf> componentImgList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(fileInfs)) {
            for (FileInf inf : fileInfs) {
                if (inf.getImgType().equals("1")) {
                    commonImgList.add(inf);
                } else {
                    componentImgList.add(inf);
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("commonImgList", commonImgList);
        result.put("componentImgList", componentImgList);
        return AjaxResult.success(result);
    }

    @PostMapping("/updatePageStatus")
    @ResponseBody
    public AjaxResult updatePageStatus(Page page) {
        this.pageService.updatePage(page);
        return success();
    }

    @GetMapping("/deleteImg")
    public String deleteImg(Long id, ModelMap modelMap) {
        modelMap.put("id", id);
        return prefix + "/deleteImg";
    }

    @PostMapping("/listImg")
    @ResponseBody
    public TableDataInfo listImg(Long id) {
        FileInf fileInf = new FileInf();
        fileInf.setObjectId(id);
        fileInf.setObjectType("2");
        fileInf.setImgType(null);
        List<FileInf> fileInfs = this.fileInfoService.selectFileInfoList(fileInf);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(fileInfs);
        rspData.setTotal(fileInfs.size());
        return rspData;
    }
    @PostMapping("/deleteImg")
    @ResponseBody
    public AjaxResult deleteImg(Long id) {
        this.fileInfoService.deleteFileInfoById(id);
        return success();
    }
    @PostMapping("/deleteImgs")
    @ResponseBody
    public AjaxResult deleteImg(String ids) {
        this.fileInfoService.deleteFileInfoByIds(ids);
        return success();
    }


}
